#include "backuppage.h"
#include "ui_backuppage.h"
#include "backuptable.h"
#include "sql/mysql/MysqlMgr.h"
#include "usermgr.h"
#include "web/tcpmgr.h"
#include <qjsondocument.h>
#include <qjsonobject.h>

BackupPage::BackupPage(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::BackupPage)
{
    ui->setupUi(this);

    // connect(m_mainWindow, &MainWindow::refresh, this, &BackupPage::pullData);
    connect(TcpMgr::GetInstance().get(), &TcpMgr::sig_getBackupInfoResponse
            , this, &BackupPage::handlePullDataResponse);
}

BackupPage::~BackupPage()
{
    delete ui;
}

void BackupPage::setSeacher(SearchEngine<Page::PAGE_BACKUP> *searcher)
{
    m_searcherPtr = searcher;
}

void BackupPage::scrollToItem(qint64 fileId)
{
    ui->backupTable->scrollToItem(fileId);
}

void BackupPage::setMainWindow(MainWindow *mainwindow)
{
    m_mainWindow = mainwindow;

    connect(m_mainWindow, &MainWindow::refresh, this, &BackupPage::pullData);
}

//改为从ResServer->mysql: file_info表拉取50条记录
void BackupPage::pullData()
{
    qDebug() << "正在拉取第" << m_currentPage << "页数据";

    // 构建JSON请求数据
    QJsonObject reqJson;
    reqJson["uid"] = UserMgr::GetInstance()->uid();
    reqJson["limit"] = m_pageSize;  // 设置为50
    reqJson["offset"] = (m_currentPage - 1) * m_pageSize;

    // 转换为JSON字符串并转换为QByteArray
    QByteArray req = QJsonDocument(reqJson).toJson(QJsonDocument::Compact);

    emit TcpMgr::GetInstance()->sig_sendGetBackupInfoRequest(req);
    // QList<FileInfo> records = MysqlMgr::GetInstance()->GetFilesByUser(
    //     UserMgr::GetInstance()->uid(),
    //     m_pageSize,
    //     (m_currentPage - 1) * m_pageSize
    //     );

    //  if(records.isEmpty()) {
    //     qDebug() << "未查询到历史记录";
    //     return;
    // }
    // // 使用记录
    // for (const FileInfo& record : records) {
    //     SearchMetaData<Page::PAGE_BACKUP> meta = record.toBackUpMetaData();
    //     m_searcherPtr->insertRecord(meta.fileName, meta.fileId, meta);
    //     ui->backupTable->appendRecord(record);
    //     //qDebug()<<record.fileId;
    // }

    // // 更新分页状态
    // if (records.size()  < m_pageSize) {
    //     qDebug() << "最后一页数据，共" << records.size()  << "条";
    // } else {
    //     m_currentPage++;  // 准备加载下一页
    // }
}

void BackupPage::handlePullDataResponse(const QByteArray &response)
{
    //处理错误，使用记录...
}

void BackupPage::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    painter.fillRect(rect(),  QColor(248, 250, 255)); // RGB颜色
    // 可选：调用基类绘制其他内容（如边框）
    QWidget::paintEvent(event);
}

void BackupPage::on_Selected_DeleteAllSelectedBtn_clicked()
{
    //删除备份逻辑暂时不做
}


void BackupPage::on_Selected_DownloadBtn_clicked()
{
    ui->backupTable->downloadAllSelected();
}

